package com.example.mygrade.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.example.mygrade.domain.Student;
import com.example.mygrade.exception.REnum;
import com.example.mygrade.exception.RException;
import com.example.mygrade.mapper.StudentMapper;
import com.example.mygrade.repository.StudentRepository;
import com.example.mygrade.service.StudentService;
import com.example.mygrade.vo.Import;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
@Component
public class StudentImplService implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

//    @Autowired
//    private StudentMapper studentMapper;

    Class<StudentMapper> studentMapperClass = StudentMapper.class;
    ExtInvokeHandler handler = new ExtInvokeHandler();

    StudentMapper studentMapper = (StudentMapper) Proxy.newProxyInstance(studentMapperClass.getClassLoader(),new Class[]{studentMapperClass},handler);
//    public static Object newProxyInstance(ClassLoader loader,
//                                          Class<?>[] interfaces,
//                                          InvocationHandler h){
//    }

    class ExtInvokeHandler implements InvocationHandler  {

        /// 只有执行mapper接口方法时才会走 invoke 方法
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

            if(Object.class.equals(method.getDeclaringClass())){
                // 如果调用了 Object 的方法，使用当前类的方法；，因为 UserMapperExt 没有实例化，不能直接调用UserMapperExt里的方法；
                return method.invoke(this,args);
            }
            // 不管走mapper的哪个方法，返回值都是 1 ，入股类型不匹配则会抛出异常
            return 1;
        }
    }

//    SqlSession sqlSession = getSqlSession();
    public List<Student> findAll() throws Exception{

        List<Student> allStudent = studentRepository.findAll();
        if(allStudent.size() > 0){
            return allStudent;
        }else {
            throw new RException(REnum.UNKOWN_ERR);
        }
    }

    /**
     * 按id进行查询
     * @param id
     * @return
     */
    public Student findById(Integer id){
        Student student = studentRepository.findById(id).orElse(null);
        return student;
    }

//    /**
//     * 按姓名进行查询
//     * @param name
//     * @return
//     */
//    public List<Student> findBySname(String name){
//        return studentRepository.findBySnameLike(name);
//    }

    public Student findBySnameLike(String name){
        return studentRepository.findBySnameLike(name);
    }

    public List<Student> findBySno(String sno){
        return studentRepository.findBySno(sno);
    }
    /**
     * 根据学号和姓名进行查询
     * @param name
     * @param sno
     * @return
     */
    public List<Student> findBySnameAndSno(String name,String sno) throws Exception{
        List<Student> bySnameAndSno = studentRepository.findBySnameAndSno(name,sno);
//        if (bySnameAndSno.size() > 0){
//            return bySnameAndSno;
//        }
//        else {
//            throw new RException(REnum.LOGIN_ERR);
//        }
        return bySnameAndSno;
    }

    public List<Student> findBySnameAndPassword(String name,String password){

        return studentRepository.findBySnameAndPassword(name,password);
    }

    public Student insert(Student student){
        studentRepository.save(student);
        return student;
    }

    public Student update(Student student){
        return studentRepository.save(student);
    }


    public void delete(Integer id){
        Student student = new Student();
        student.setId(id);
        studentRepository.delete(student);
    }

    public void delete(Integer[] arr){
        Student student = new Student();
        for (int i = 0;i < arr.length;i++){
            student.setId(arr[i]);
            studentRepository.delete(student);
        }
    }

    public Page<Student> findAll(Pageable pageable){
        return studentRepository.findAll(pageable);
    }

    public Page<Student> findAll(Example<Student> student,Pageable pageable){
        return studentRepository.findAll(student,pageable);
    }

    @Override
    public int insertStudent(MultipartFile file) throws Exception {
        int result = 0;
        //存放excel表中所有数据
        List<Student> eaxmList = new ArrayList<>();

        //file.getOriginalFilename()方法 得到上传时的文件名
        String fileName = file.getOriginalFilename();
        //截取文件名的后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);

        //file.getInputStream()方法  返回InputStream对象 读取文件的内容
        InputStream ins = file.getInputStream();
        Workbook wb = null;
        /*判断文件后缀
            XSSF － 提供读写Microsoft Excel OOXML XLSX格式档案的功能。
            HSSF － 提供读写Microsoft Excel XLS格式档案的功能。*/
        if(suffix.equals("xlsx")){
            wb = new XSSFWorkbook(ins);
        }else{
            wb = new HSSFWorkbook(ins);
        }

        //获取excel表单的sheet对象
        Sheet sheet = wb.getSheetAt(0);
        //如果sheet不为空，就开始遍历表中的数据
        if(null != sheet){
            //line = 1 :从表的第2行开始获取记录
            for(int line = 1; line <= sheet.getLastRowNum();line++){

                //excel表单的sheet的行对象
                Row row = sheet.getRow(line);

                //如果某行为空，跳出本行
                if(null == row){
                    continue;
                }
                //获取第一个单元格的内容
                //表示获取单元格中的内容是String字符串类型
                row.getCell(0).setCellType(CellType.STRING);
                row.getCell(1).setCellType(CellType.STRING);
                row.getCell(2).setCellType(CellType.STRING);

                String sno = row.getCell(0).getStringCellValue();
                String sname = row.getCell(1).getStringCellValue();
                String sex = row.getCell(2).getStringCellValue();

                //这解决的是单元格内读取的日期是天（写的是年月日，但是读取后变成了总天数），需要休眠操作在转换成年月日格式
//                Calendar calendar = new GregorianCalendar(1900,0,-1);
//                Date d = calendar.getTime();
//                Date examtime = DateUtils.addDays(d,Integer.valueOf(examti);
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                String timeFormat = sdf.format(examtime);


                //获取第二个单元格的内容
                //格式是number
//                Integer sage = Integer.valueOf(row.getCell(3).getStringCellValue());
//
//                Integer classid = Integer.valueOf(row.getCell(4).getStringCellValue());
//                Integer gradeid = Integer.valueOf(row.getCell(5).getStringCellValue());
                Double sage1 = row.getCell(3).getNumericCellValue();
                int sage = new Double(sage1).intValue();
                row.getCell(4).setCellType(CellType.STRING);
                String password = row.getCell(4).getStringCellValue();

                Double classid1 = row.getCell(5).getNumericCellValue();
                int classid = new Double(classid1).intValue();
                Double gradeid1 = row.getCell(6).getNumericCellValue();
                int gradeid = new Double(gradeid1).intValue();

                row.getCell(7).setCellType(CellType.STRING);
                String mid = row.getCell(7).getStringCellValue();


                Student eaxm = new Student();

                eaxm.setSno(sno);
                eaxm.setSname(sname);
                eaxm.setSex(sex);
                eaxm.setSage(sage);
                eaxm.setPassword(password);
                eaxm.setClassid(classid);
                eaxm.setGradeid(gradeid);
                eaxm.setMid(mid);

                eaxmList.add(eaxm);

            }
//            //这其实可以在做一下 判断  是否数据库里已经存在了你要导入数据，我么得写，不想写，懒，难受
            for(Student eaxm:eaxmList){

//                List<Student> students = studentRepository.findBySnameLike(eaxm.getSname());
//                if (students.size() == 0){
//                    result = studentMapper.addExcelStudent(eaxm);
                Student student = new Student();
                student.setSno(eaxm.getSno());
                student.setSname(eaxm.getSname());
                student.setSex(eaxm.getSex());
                student.setSage(eaxm.getSage());
                student.setPassword(eaxm.getPassword());
                student.setClassid(eaxm.getClassid());
                student.setGradeid(eaxm.getGradeid());
                student.setMid(eaxm.getMid());
                studentRepository.save(student);
                if(student != null){
                    result = 1;
                }
//                    System.out.println(result);
//                }

            }
        }
        return result;
    }

    /**
     * excel导出学生表
     * @param response
     */
    public void exportStudent(HttpServletResponse response){
        try {
            //从数据库查询到数据
            List<Student> students = studentRepository.findAll();

            //设置信息头，告诉浏览器内容为excel类型
            response.setHeader("content-Type", "application/vnd.ms-excel");
            //设置下载名称
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("学生信息表.xls", StandardCharsets.UTF_8.name()));
            //字节流输出
            ServletOutputStream out = response.getOutputStream();
            //设置excel参数
            ExportParams params = new ExportParams();
            //设置sheet名
            params.setSheetName("学生列表");
            //设置标题
            params.setTitle("学生信息表");

            //转成对应的类型;要不然会报错，虽然也可以导出成功。
            List<Import> exportUsers = changeType(students);
            //导入excel
            Workbook workbook = ExcelExportUtil.exportExcel(params, Import.class,exportUsers );
            //写入
            workbook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 转成导出vo
     *
     * @param users  users集合
     */
    private List<Import> changeType(List<Student> users) {
        List<Import> res = new ArrayList<>();
        for (Student user : users) {
            Import exportUser = new Import(user);
            res.add(exportUser);
        }
        return res;
    }
}

